package com.fengniao.goods.controller;

import com.fengniao.goods.pojo.Category;
import com.fengniao.goods.service.CategoryService;
import com.github.pagehelper.PageInfo;
import entity.DBOperUtil;
import entity.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @author lanhai
 * @date 2021/7/5 16:41
 */
@RestController
@RequestMapping("/category")
@CrossOrigin
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @GetMapping("/list/{pid}")
    public Result<List<Category>> findByParentId(@PathVariable Integer pid) {
        List<Category> categories = categoryService.findByParentId(pid);
        return Result.data(categories);
    }

    @GetMapping
    public Result<List<Category>> findAll() {
        List<Category> all = categoryService.findAll();
        return Result.data(all);
    }

    @GetMapping("/{id}")
    public Result<Category> findById(@PathVariable Integer id) {

        return Result.data(categoryService.findById(id));
    }

    @PostMapping
    public Result add(@RequestBody Category category) {

        int flag = categoryService.add(category);
        DBOperUtil.checkDBOper(flag, "添加分类失败");
        return Result.ok("添加分类成功");
    }

    @PutMapping("/{id}")
    public Result revise(@PathVariable Integer id, @RequestBody Category category) {

        category.setId(id);
        int flag = categoryService.revise(category);
        DBOperUtil.checkDBOper(flag, "添加分类失败");
        return Result.ok("修改分类成功");
    }

    @DeleteMapping("/{id}")
    public Result remove(@PathVariable Integer id) {

        int flag = categoryService.remove(id);
        DBOperUtil.checkDBOper(flag,"删除分类失败");
        return Result.ok("删除分类成功");
    }

    @PostMapping("/search")
    public Result<List<Category>> findList(@RequestBody Category category) {

        List<Category> list = categoryService.findList(category);
        return Result.data(list);
    }

    @GetMapping("/search/{num}/{size}")
    public Result<PageInfo<Category>> findPage(@PathVariable("num") Integer num,
                                            @PathVariable("size") Integer size) {

        PageInfo<Category> page = categoryService.findPage(num, size);
        return Result.data(page);
    }

    @PostMapping("/search/{num}/{size}")
    public Result<PageInfo<Category>> findPage(@RequestBody(required = false) Category category,
                                            @PathVariable("num") Integer num,
                                            @PathVariable("size") Integer size) {

        PageInfo<Category> page = categoryService.findPage(category, num, size);
        return Result.data(page);
    }
}
